package educar.controllers;


import javax.swing.JOptionPane;
import javax.swing.JTable;

import educar.gui.IView;
import educar.idioma.Locale;
import educar.models.User;
import educar.models.userNotFound;


/**
 * Permite borrar un usuario
 */
public class DeleteUserController implements IController {
	private IView panel;
	private JTable table;
	
	/**
	 * Constructor
	 * @param table "JTable sobre la cual se busca el usuario a borrar"
	 */
	public DeleteUserController(JTable table) {
		this.table = table;
	}


	public void process(String model){
		/*obtengo la fila seleccionada*/
		final int fila = table.getSelectedRow();
		if (fila == -1) {
			JOptionPane.showMessageDialog(null,Locale.FIRST_SELECT_ROW,Locale.NOT_ROW_SELECTED,JOptionPane.WARNING_MESSAGE);
		}
		else {
			try {				
				User old = User.getUserByUsername(table.getModel().getValueAt(fila, 1).toString());
				/*Si no es el admin permito borrarlo*/
				if (!old.getUsername().equals("admin")) {
					int n = JOptionPane.showConfirmDialog(null,Locale.DELETE+" "+Locale.USERS+": "+old.getUsername(),Locale.DELETE+" "+Locale.USERS,JOptionPane.YES_NO_OPTION);
					if (n == JOptionPane.OK_OPTION) {
							old.destroy();
							/*uso el present para refrescar la tabla*/
							panel.present(model);			
						}
				}
				/*Si es el admin aviso que no se puede borrar*/
				else {
					JOptionPane.showMessageDialog(null,Locale.CANT_DELETE+" "+Locale.USERS+": "+old.getUsername(),Locale.DELETE+" "+Locale.USERS,JOptionPane.WARNING_MESSAGE);
				}
			} catch (userNotFound e1){
				JOptionPane.showMessageDialog(null,Locale.NOT_VALID_USER,Locale.ERROR,JOptionPane.WARNING_MESSAGE);
			}			
			
		}
		
	}

	public void setView(IView view) {
		this.panel = view;
	}

}
